#include "process_pool.h"

int main(int argc,char**argv)
{
    ARGS_CHECK(argc,4);
    int process_num=atoi(argv[3]);
    process_data_t *p_manage=(process_data_t *)calloc(process_num,sizeof(process_data_t));
    make_child(p_manage,process_num);
    int socket_fd;//这是父进程需要监测的是否有客户连入
    tcp_init(&socket_fd,argv[1],argv[2]);
    printf("socket_fd=%d\n",socket_fd);
    int epfd=epoll_create(1);
    int ret=epoll_add(epfd,socket_fd);
    SELFFUNC_ERR_CHECK(ret,"epoll_add");
    int i;
    for(i=0;i<process_num;i++)//监控每个子进程的管道
    {
        ret=epoll_add(epfd,p_manage[i].fd);
        SELFFUNC_ERR_CHECK(ret,"epoll_add");
    }
    int new_fd,j;
    int ready_num;
    //用于存放已经发来请求的描述符
    struct epoll_event *evs=(struct epoll_event *)calloc(process_num+1,sizeof(struct epoll_event));
    struct sockaddr_in cli_addr;
    char flag;
    while(1)
    {
        ready_num=epoll_wait(epfd,evs,process_num+1,-1);
        for(i=0;i<ready_num;i++)
        {
            //此时若有客户端发来请求
            if(evs[i].data.fd==socket_fd)
            {
                bzero(&cli_addr,sizeof(cli_addr));
                socklen_t cli_len=sizeof(cli_addr);
                new_fd=accept(socket_fd,(struct sockaddr *)&cli_addr,&cli_len);
                printf("%s %d is connect\n",inet_ntoa(cli_addr.sin_addr),ntohs(cli_addr.sin_port));
                for(j=0;j<process_num;j++)
                {
                    if(p_manage[j].busy==0)
                    {
                        send_fd(p_manage[j].fd,new_fd);
                        p_manage[j].busy=1;
                        printf("child %d is busy\n",p_manage[j].pid);
                        break;
                    }
                }
                close(new_fd);
            }
            //如果此时是子进程发的完成任务的消息
            for(j=0;j<process_num;j++)
            {
                if(evs[i].data.fd==p_manage[j].fd)
                {
                    read(p_manage[j].fd,&flag,sizeof(flag));//把数据读出来
                    p_manage[j].busy=0;
                    printf("child %d is not busy\n",p_manage[j].pid);
                    break;
                }
            }
        }
        return 0;
    }
}